package com.burgeon.backend.college.control_panel.service.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;


public class PDFToImageUtil {

    private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);

    private synchronized static void runToPng(int i, String filePath, String id, PDFRenderer renderer) {

        try {
            // 方式1,第二个参数是设置缩放比(即像素)
            BufferedImage image = renderer.renderImageWithDPI(i, 100);
            // 方式2,第二个参数是设置缩放比(即像素)
            // BufferedImage image = renderer.renderImage(i, 2.5f);

            ImageIO.write(image, "PNG",
                    new File(filePath + id + "//" + i + ".png"));

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static int PdfToPng(String id, String filePath, String fileName) {
        File file = new File(filePath + fileName);//"E://xxxxxx//111.pdf"
        System.err.println(file.getName());
        Date date = new Date();
        long s = date.getTime();
        long e;

        File arrtDest = new File(filePath + id + "//a");

        if (!arrtDest.getParentFile().exists()) {
            arrtDest.getParentFile().mkdirs();
        }

        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
               /* // 方式1,第二个参数是设置缩放比(即像素)
                BufferedImage image = renderer.renderImageWithDPI(i, 70);
                // 方式2,第二个参数是设置缩放比(即像素)
                // BufferedImage image = renderer.renderImage(i, 2.5f);
                ImageIO.write(image, "PNG",
                        new File(filePath+id+"//"+i+".png"));*/
                int finalI = i;
                Runnable task = () -> {
                    System.out.println("执行任务啦");

                    runToPng(finalI, filePath, id, renderer);
                    System.err.println(123);

                };
                // 3. 向线程池提交任务
                fixedThreadPool.execute(task);

            }
            e = new Date().getTime();
            System.err.println((e - s) / 1000);
            return pageCount;
        } catch (IOException es) {
            es.printStackTrace();
        }

        return 0;

    }


    public static void main(String[] args) {
//        File file = new File("E://xxxxxx//111.pdf");
//        System.err.println(file.getName());
        String id = "00";
        String filePath = "E://xxxxxx//";
        String fileName = "11.pdf";
        int i = PdfToPng(id, filePath, fileName);
        System.err.println(i);
    }
}
